package cn.edu.hzvtc.interceptor;

import cn.edu.hzvtc.pojo.User;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler) throws Exception {
        Boolean flg = true;
        //获取请求的uri 去除http:localhost:8080这部分剩下的
        String uri = request.getRequestURI();
        System.out.println(uri);
        //utl除了login.jsp是可以公开访问的，其他的url都进行拦截控制

        if (uri.indexOf("/login") >= 0 || uri.indexOf("/commons/") >= 0) {
            return flg;
        }

        //获取session
        HttpSession session = request.getSession();
        System.out.println(session.getId());
        User user = (User) session.getAttribute("loginUser");
        System.out.println(user.getUserType());
        //判断session中是否有用户数据，如果有，则返回true，继续向下执行
        if (user != null) {
            if (uri.indexOf("/area") >= 0) {
                if (user.getUserType() != 1) {
                    flg = false;
                }
            }
            if (uri.indexOf("/unit") >= 0) {
                if (user.getUserType() != 2) {
                    flg = false;
                }
            }
            if (uri.indexOf("/msg") >= 0) {
                if (user.getUserType() != 3) {
                    System.out.println(user.getUserType());
                    flg = false;
                }
            }
        } else {
            flg = false;
        }
        if (!flg) {
            response.sendRedirect(request.getContextPath());
            return false;
        }
        return flg;
    }
}
